<template>
  <div class="leave-container">
    <el-card class="page-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><Document /></el-icon>
            <span class="header-title">请假申请</span>
          </div>
          <el-button type="primary" @click="showApplyDialog = true" size="large">
            <el-icon><Plus /></el-icon>
            <span>申请请假</span>
          </el-button>
        </div>
      </template>
      
      <el-tabs v-model="activeTab" class="leave-tabs">
        <el-tab-pane label="我的请假" name="my">
          <el-table :data="myLeaveList" style="width: 100%" stripe :empty-text="'暂无请假记录'">
            <el-table-column prop="type" label="类型" width="120" align="center">
              <template #default="scope">
                <el-tag v-if="scope.row.type === 'ANNUAL'" type="success" effect="dark">年假</el-tag>
                <el-tag v-else-if="scope.row.type === 'SICK'" type="warning" effect="dark">病假</el-tag>
                <el-tag v-else-if="scope.row.type === 'PERSONAL'" type="info" effect="dark">事假</el-tag>
                <el-tag v-else effect="dark">调休</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="startDate" label="开始日期" width="120" align="center">
              <template #default="scope">
                <span>{{ formatDate(scope.row.startDate) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="endDate" label="结束日期" width="120" align="center">
              <template #default="scope">
                <span>{{ formatDate(scope.row.endDate) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="days" label="天数" width="80" align="center">
              <template #default="scope">
                <span class="days-text">{{ scope.row.days }}天</span>
              </template>
            </el-table-column>
            <el-table-column prop="reason" label="原因" min-width="200" />
            <el-table-column prop="status" label="状态" width="100" align="center">
              <template #default="scope">
                <el-tag v-if="scope.row.status === 'APPROVED'" type="success">已通过</el-tag>
                <el-tag v-else-if="scope.row.status === 'PENDING'" type="warning">待审核</el-tag>
                <el-tag v-else type="danger">已拒绝</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="待审批" name="pending" v-if="isManager">
          <el-table :data="pendingLeaveList" style="width: 100%" stripe :empty-text="'暂无待审批记录'">
            <el-table-column prop="type" label="类型" width="120" align="center">
              <template #default="scope">
                <el-tag v-if="scope.row.type === 'ANNUAL'" type="success" effect="dark">年假</el-tag>
                <el-tag v-else-if="scope.row.type === 'SICK'" type="warning" effect="dark">病假</el-tag>
                <el-tag v-else-if="scope.row.type === 'PERSONAL'" type="info" effect="dark">事假</el-tag>
                <el-tag v-else effect="dark">调休</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="startDate" label="开始日期" width="120" align="center">
              <template #default="scope">
                <span>{{ formatDate(scope.row.startDate) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="endDate" label="结束日期" width="120" align="center">
              <template #default="scope">
                <span>{{ formatDate(scope.row.endDate) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="days" label="天数" width="80" align="center">
              <template #default="scope">
                <span class="days-text">{{ scope.row.days }}天</span>
              </template>
            </el-table-column>
            <el-table-column prop="reason" label="原因" min-width="200" />
            <el-table-column label="操作" width="180" align="center" fixed="right">
              <template #default="scope">
                <el-button size="small" type="success" @click="handleApprove(scope.row.id, 'APPROVED')">
                  <el-icon><Check /></el-icon>
                  通过
                </el-button>
                <el-button size="small" type="danger" @click="handleApprove(scope.row.id, 'REJECTED')">
                  <el-icon><Close /></el-icon>
                  拒绝
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    
    <el-dialog 
      v-model="showApplyDialog" 
      title="申请请假" 
      width="550px"
      class="leave-dialog"
    >
      <el-form :model="leaveForm" label-width="100px" label-position="left">
        <el-form-item label="请假类型">
          <el-select v-model="leaveForm.type" style="width: 100%" size="large">
            <el-option label="年假" value="ANNUAL" />
            <el-option label="病假" value="SICK" />
            <el-option label="事假" value="PERSONAL" />
            <el-option label="调休" value="ADJUSTMENT" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期">
          <el-date-picker 
            v-model="leaveForm.startDate" 
            type="date" 
            style="width: 100%" 
            size="large"
            placeholder="选择开始日期"
          />
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker 
            v-model="leaveForm.endDate" 
            type="date" 
            style="width: 100%" 
            size="large"
            placeholder="选择结束日期"
          />
        </el-form-item>
        <el-form-item label="请假原因">
          <el-input 
            v-model="leaveForm.reason" 
            type="textarea" 
            :rows="4"
            placeholder="请输入请假原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showApplyDialog = false">取消</el-button>
        <el-button type="primary" @click="handleApply" size="large">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import request from '../utils/request'
import { ElMessage } from 'element-plus'
import { Document, Plus, Check, Close } from '@element-plus/icons-vue'

export default {
  name: 'Leave',
  components: {
    Document,
    Plus,
    Check,
    Close
  },
  setup() {
    const activeTab = ref('my')
    const showApplyDialog = ref(false)
    const myLeaveList = ref([])
    const pendingLeaveList = ref([])
    const leaveForm = ref({
      type: 'ANNUAL',
      startDate: '',
      endDate: '',
      reason: ''
    })
    
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const isManager = computed(() => {
      return userInfo.role === 'MANAGER' || userInfo.role === 'HR'
    })
    
    const formatDate = (dateStr) => {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }
    
    const loadMyLeaves = async () => {
      try {
        const res = await request.get('/leave/my')
        myLeaveList.value = res.data || []
      } catch (error) {
        ElMessage.error('加载请假记录失败')
      }
    }
    
    const loadPendingLeaves = async () => {
      if (!isManager.value) return
      try {
        const res = await request.get('/leave/pending')
        pendingLeaveList.value = res.data || []
      } catch (error) {
        ElMessage.error('加载待审批记录失败')
      }
    }
    
    const handleApply = async () => {
      if (!leaveForm.value.startDate || !leaveForm.value.endDate) {
        ElMessage.warning('请选择日期')
        return
      }
      
      // 格式化日期为 YYYY-MM-DD
      const formatDateForSubmit = (date) => {
        if (!date) return ''
        const d = new Date(date)
        const year = d.getFullYear()
        const month = String(d.getMonth() + 1).padStart(2, '0')
        const day = String(d.getDate()).padStart(2, '0')
        return `${year}-${month}-${day}`
      }
      
      const start = new Date(leaveForm.value.startDate)
      const end = new Date(leaveForm.value.endDate)
      const days = Math.ceil((end - start) / (1000 * 60 * 60 * 24)) + 1
      
      if (days <= 0) {
        ElMessage.warning('结束日期必须大于开始日期')
        return
      }
      
      try {
        await request.post('/leave/apply', {
          type: leaveForm.value.type,
          startDate: formatDateForSubmit(leaveForm.value.startDate),
          endDate: formatDateForSubmit(leaveForm.value.endDate),
          days: days,
          reason: leaveForm.value.reason || ''
        })
        ElMessage.success('请假申请已提交')
        showApplyDialog.value = false
        leaveForm.value = {
          type: 'ANNUAL',
          startDate: '',
          endDate: '',
          reason: ''
        }
        loadMyLeaves()
      } catch (error) {
        ElMessage.error(error.message || '申请失败')
      }
    }
    
    const handleApprove = async (leaveId, status) => {
      try {
        await request.post('/leave/approve', {
          leaveId: leaveId,
          status: status
        })
        ElMessage.success('审批完成')
        loadPendingLeaves()
        loadMyLeaves()
      } catch (error) {
        ElMessage.error(error.message || '审批失败')
      }
    }
    
    onMounted(() => {
      loadMyLeaves()
      loadPendingLeaves()
    })
    
    return {
      activeTab,
      showApplyDialog,
      myLeaveList,
      pendingLeaveList,
      leaveForm,
      isManager,
      formatDate,
      handleApply,
      handleApprove
    }
  }
}
</script>

<style scoped>
.leave-container {
  width: 100%;
  height: 100%;
}

.page-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  font-size: 24px;
  color: #667eea;
}

.header-title {
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
}

.leave-tabs {
  margin-top: 8px;
}

.days-text {
  font-weight: 600;
  color: #409eff;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #333;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 16px 0;
}

:deep(.el-tabs__item) {
  font-size: 15px;
  font-weight: 500;
}

:deep(.el-tabs__item.is-active) {
  color: #409eff;
  font-weight: 600;
}

:deep(.el-tabs__active-bar) {
  background-color: #409eff;
}
</style>

